 #!/usr/bin/env python3
"""
调试LightGBM的特征和预测过程
"""

import sys
import os
from pathlib import Path
import numpy as np

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from backend.service.prediction_service import PredictionService

def debug_lightgbm_features():
    """调试LightGBM的特征和预测过程"""
    print("🔍 调试LightGBM的特征和预测过程...")
    
    # 测试日期
    test_dates = ["2025-07-20", "2025-07-21"]
    
    prediction_service = PredictionService()
    
    # 确保模型已加载
    print("🔄 加载模型...")
    success = prediction_service.load_models()
    print(f"📊 模型加载结果: {success}")
    
    for target_date in test_dates:
        print(f"\n📅 测试日期: {target_date}")
        
        # 准备特征
        features = prediction_service.prepare_prediction_features(target_date)
        if features is None:
            print(f"❌ 特征准备失败")
            continue
            
        print(f"📊 特征形状: {features.shape}")
        print(f"📊 特征范围: {features.min():.4f} - {features.max():.4f}")
        
        # 检查特征的前几个值
        print(f"📊 特征前10个值: {features[0, :10].tolist()}")
        
        # 测试LightGBM模型的原始预测
        model = prediction_service.models.get('lightgbm')
        if model is not None:
            print(f"🤖 测试LightGBM模型原始预测...")
            
            # 直接调用模型预测
            raw_pred = model.predict(features)
            print(f"📊 原始预测形状: {raw_pred.shape}")
            print(f"📊 原始预测范围: {raw_pred.min():.4f} - {raw_pred.max():.4f}")
            print(f"📊 原始预测前5个值: {raw_pred.flatten()[:5]}")
            
            # 检查是否是单输出模型
            if raw_pred.ndim == 1:
                if len(raw_pred) == 1:
                    print(f"⚠️  检测到单输出模型，预测值: {raw_pred[0]}")
                elif len(raw_pred) == 96:
                    print(f"✅ 多输出模型，96个时间点")
                else:
                    print(f"❓ 异常输出维度: {len(raw_pred)}")
            elif raw_pred.ndim == 2:
                if raw_pred.shape[1] == 1:
                    print(f"⚠️  检测到单输出模型，预测值: {raw_pred[0, 0]}")
                elif raw_pred.shape[1] == 96:
                    print(f"✅ 多输出模型，96个时间点")
                else:
                    print(f"❓ 异常输出维度: {raw_pred.shape}")
        
        # 检查特征是否相同
        if target_date == test_dates[0]:
            first_features = features.copy()
        else:
            if np.array_equal(first_features, features):
                print(f"❌ 问题确认: 不同日期的特征完全相同!")
                print(f"   这解释了为什么预测结果相同")
            else:
                print(f"✅ 特征不同，但预测结果相同")
                
                # 计算特征差异
                diff = np.abs(first_features - features)
                max_diff = diff.max()
                mean_diff = diff.mean()
                print(f"📊 最大差异: {max_diff:.4f}")
                print(f"📊 平均差异: {mean_diff:.4f}")

if __name__ == "__main__":
    debug_lightgbm_features()